<?php
namespace app\home\controller;
use app\common\controller\AuthBase;
use think\Db;
/**
 * @title 用户管理
 * @description 接口说明
 * @group AUTH权限
 */
class User extends AuthBase{
    function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\User();
    }

    //人员列表
    public function lst(){
        //查询条件
        $params = input();
        //启用--0 || 禁用 --1
        if(isset($params['status']) && $params['status'] !== ''){
            $map['u.status'] = ['eq',$params['status']];
        }
        //模糊搜索
        if(!empty($params['vauge'])){
            $vauge = $params['vauge'];
            $map['u.name|u.nick|u.mobile'] = ['like',"%$vauge%"];
        }
        $map['u.deleted'] = ['eq',0];
        //$field = "u.id,u.name,u.nick,u.mobile,u.status,group_concat(g.id) as gid,g.title";
        $field = "u.id,max(u.name) as name,max(u.deptid) as dept,max(u.nick) as nick,max(u.mobile) as mobile,max(u.status) as status,GROUP_CONCAT(DISTINCT a.group_id) as group_ids";
        $page = !empty($params['page']) ? $params['page'] : 1;
        $length = !empty($params['page_number']) ? $params['page_number']: 100;
        $start = ($page - 1) * $length;
        $limit = $start.",".$length;
        $count = $this->model->where('deleted',0)->count('id');
        $list = $this->model->getList($map,$field,[],'',$limit);
        foreach ($list as $k => $v){
            $list[$k]['status'] = $list[$k]['status'] == 0 ? true : false;
            if(empty($v['name'])){
                $list[$k]['name'] = $v['nick'];
            }
            unset($list[$k]['nickname']);
        }
        $json = ['code' => 0,'msg' => '成功','data' => ['page'=>$page,'total'=>$count,'list' => $list,'dept'=>$this->model->dept]];
        return json($json);
    }

    //添加
    public function add(){
        if(request()->isPost()){
            return self::_add();
        }
    }


    //删除
    public function remove(){
        $params = input();
        $ids = !empty($params['id']) ? $params['id'] : '';
        //$isdel = !empty($params['isdel']) ? $params['isdel'] : '';
        if(empty($ids)){
            return json(['msg'=>'参数错误','code'=>1]);
        }
//        if(is_array($ids)){
//            //多选
//            $map = ['id' => ['in',$ids],'memberid' => MEMBER_ID];
//            $admin_map = ['u.id' => ['in',$ids],'u.memberid' => MEMBER_ID];
//            $client_map = ['sourceid' => ['in',$ids],'memberid' => MEMBER_ID,'deleted' => 0];
//        }else{
//            $map = ['id' => $ids,'memberid' => MEMBER_ID];
//            $admin_map = ['u.id' => $ids,'u.memberid' => MEMBER_ID];
//            $client_map = ['sourceid' => ['eq',$ids],'memberid' => MEMBER_ID,'deleted' => 0];
//        }

//        if(empty($isdel)){
//            $have_client = Db::table('dt_user')->where($client_map)->count();
//            if($have_client){
//                return json(['msg'=>'当前选择用户存在客户，是否删除？','code' => 0]);
//            }else{
//                return json(['msg'=>'是否确认删除所选人员？','code' => 0]);
//            }
//        }
        $admin_map['u.isadmin'] = ['eq',1];
        $admin_map['u.id'] = ['eq',$ids];
        $field = "u.id,u.name";
        $admin_list = $this->model->getList($admin_map,$field);
        if($admin_list){
            $names = [];
            foreach ($admin_list as $k => $v){
                $names[] = $v['name'];
            }
            $names_str = implode(',',$names);
            return json(['msg'=>'不能操作超级管理员【'.$names_str.'】','code'=>1]);
        }

        $res = $this->model->remove(['id' => $ids]);
        if($res){
            //删除人员后把客户跟进人清空
            //$setnull = Db::table('dt_user')->where($client_map)->update(['sourceid' => 0]);
            return json(['msg'=>'删除成功','code'=>0]);
        }else{
            return json(['msg'=>'删除失败','code'=>1]);
        }
    }

    public function info(){
        $id = input('id');
        if(empty($id) || !is_numeric($id)){
            return json(['msg'=>'参数错误','code'=>1]);
        }

        $map = ['u.id' => $id,'u.memberid' => MEMBER_ID,'u.deleted' => 0];
        $field = "u.id,u.headimgurl,u.name,u.mobile,u.duty,u.show_phone,u.status,u.create_time,u.deptid,d.title as dname";
        $res = Db::table('dt_user u')
                    ->join('dt_dept d','u.deptid=d.id','left')
                    ->where($map)
                    ->field($field)
                    ->find();

        if($res){
            $group = Db::table('dt_auth_group_access a')
                            ->join('dt_auth_group g','a.group_id=g.id')
                            ->where(['uid' => $id])
                            ->field('a.group_id,g.title')
                            ->select();
            $group_name = [];
            $group_ids = [];
            foreach ($group as $k => $v){
                $group_name[] = $v['title'];
                $group_ids[] = $v['group_id'];
            }
            $res['root_name'] = implode(",", $group_name);
            $res['root'] = $group_ids;
            return json(['msg' => '成功','code' => 0,'data' => $res]);
        }else{
            return json(['msg' => '失败','code' => 1]);
        }
    }


    //添加||修改
    private function _add(){
        $params = input();
        $root = !empty($params['root']) ? $params['root'] : [];
        $params['mobile'] = !empty($params['mobile']) ? trim($params['mobile']) : '';
        $password = !empty($params['password']) ? trim($params['password']) : '';
        if(empty($params['id'])){
            $map['deleted'] = ['eq',0];

            $user_map['mobile'] = $params['mobile'];
            $user_map['deleted'] = ['eq',0];
            $item = $this->model->where($user_map)->whereOr('name',$params['name'])->find();
            if($item){
                return json(['msg'=>'登陆账号或手机号已经存在','code'=>1]);
            }
            $params['password'] = md5($password.config('salt'));
            $params['isadmin'] = 0;
            $result = $this->model->createData($params);
            $userid = $result;
        }else{
            $userid = $params['id'];
            if($password){
                $params['password'] = md5($password.config('salt'));
            }else{
                unset($params['password']);
            }

            /*$user_map['u.id'] = ['neq',$userid];
            $user_map['u.mobile'] = ['eq',$params['mobile']];
            $user_map['u.deleted'] = ['eq',0];
            $item = $this->model->getCount($user_map);
            if($item){
                return json(['msg'=>'当前手机号已经存在','code'=>1]);
            }*/
            $result = $this->model->editData($params);
        }
        if($result !== false){
            //用户权限
            if($root){
                $root = array_unique($root);
                $del_group = Db::table('hs_auth_group_access')->where(['uid'=>$userid])->delete();
                foreach ($root as $k => $v){
                    $group[$k]['group_id'] = $v;
                    $group[$k]['uid'] = $userid;
                }
                $add_group = Db::table('hs_auth_group_access')->insertAll($group);
            }
            return json(['msg'=>'操作成功','code'=>0]);
        }else{
            return json(['msg'=>'操作失败','code'=>1]);
        }
    }


    //禁用 || 启用
    public function enable(){
        $params = input();
        $id = !empty($params['id']) ? $params['id'] : '';
        $status = !empty($params['status']) ? $params['status'] : 0;

        if(!$id){
            return json(['msg'=>'参数错误','code'=>1]);
        }
        $map = ['id' => $id];

//        if(is_array($id)){
//            $map =[
//                'id' => ['in',$id],
//                'memberid' => ['eq',MEMBER_ID]
//            ];
//        }else{
//            $map = ['id' => $id,'memberid' => MEMBER_ID];
//        }
        //status = 1  禁用 else 启用;
        $list = $this->model->where($map)->field('id,name,isadmin')->select()->toarray();

        if(is_array($list)){
            foreach ($list as $k => $v){
                if($v['isadmin'] == 1){
                    return json(['msg'=>'不能操作超级管理员【'.$v['name'].'】','code'=>1]);
                }
            }
        }
        //dump($status);
        //dump($map);die;
        $save = $this->model->where($map)->update(['status' => $status]);

        if($save !== false){
            return json(['msg'=>'操作成功','code'=>0]);
        }else{
            return json(['msg'=>'操作失败','code'=>1]);
        }
    }

    //个人中心
    public function personal(){
        $map = ['u.id' => USER_ID,'u.memberid' => MEMBER_ID,'u.deleted' => 0];
        $field = "u.id,u.headimgurl,u.name,u.mobile,u.duty,u.show_phone,u.status,d.title as dname";
        $res = Db::table('dt_user u')
                    ->join('dt_dept d','u.deptid=d.id','left')
                    ->where($map)
                    ->field($field)
                    ->find();

        if($res){
            return json(['msg' => '成功','code' => 0,'data' => $res]);
        }else{
            return json(['msg' => '失败','code' => 1]);
        }
    }

    //修改资料
    public function save(){
        $params = input();
        $params['id'] = USER_ID;
        $password = !empty($params['password']) ? trim($params['password']) : '';
        if(!$params['id']){
            return json(['msg'=>'非法参数','code'=>1]);
        }
        $userInfo = Db::name('user')->where('id',$params['id'])->find();
        if($password){
            $params['password'] = md5($password.config('salt'));
            if ($userInfo['password'] == $params['password'])
                return json(['code' => 1, 'msg' => '不能与前一次密码相同。']);
        }else{
            unset($params['password']);
        }
        // 上传头像
        $res = $this->deal_upload($params['id']);
        if ($res['code'] == 1) return $res;

        $result = $this->model->editData($params);
        if($result !== false){
            return json(['msg'=>'修改成功','code'=>0]);
        }else{
            return json(['msg'=>'修改失败','code'=>1]);
        }
    }

    /**
     * @title 处理上传图片
     * @description 接口说明
     */
    public function deal_upload($id) {
        $path = "hs_system/userImg/{$id}/";
        $img = new \myclass\Imageup($path);
        $file = request()->file('file');

        if (!empty($file)) {
            $temp = $file->getInfo();
            if (strpos($temp['type'],'image') !== false) {
                //上传的图片
                $result = $img->upload_img($file,0,1);
            } else {
                //其他文件
                return ['code'=>'1','msg'=>'请上传图片'];
            }
            if ($result['code'] == 1) {
                return ['code'=>1,'msg'=>'上传失败'];
            }
            $add_data['headImg'] = $result['url'];

            //录库
            $res = $this->model->save($add_data,['id' => $id]);
            if ($res) {
                return ['code'=>0,'msg'=>'上传成功','data'=>$add_data];
            }
        }
    }

    //角色列表
    public function rulelst(){
        $map['deleted'] = ['eq',0];
        $list = Db::table('hs_auth_group')->where($map)->field('id,title')->select();

        return json(['msg'=>'成功','code'=>0,'data'=>['list' => $list]]);
    }


    /**
     * 生成小程序码添加员工
     */
    public function user_qrcode(){
        $deptid = input("deptid",0);
        if(!$deptid){
            return json(['code' => 1,'msg' => '非法参数']);
        }

        $count = Db::table('dt_wxmini_audit')->where(['memberid' => MEMBER_ID,'minis_status' => 4])->count();
        if(!$count){
            return json(['code' => 1,'msg' => '小程序还未发布成功，不能添加人员']);
        }

        $map['u.memberid'] = ['eq',MEMBER_ID];
        $map['u.isstaff'] = ['eq',1];
        $map['u.deleted'] = ['eq',0];
        $map['d.deleted'] = ['eq',0];
        $count = $this->model->getCount($map);   //统计用户总数
        $member = new \app\common\model\Member();
        $max_users = $member->where(['id' => MEMBER_ID,'deleted' => 0])->value('max_users');
        if(!$max_users){
            return json(['msg'=>'参数错误','code'=>1]);
        }
        if($max_users <= $count){
            return json(['msg'=>'用户数量超出限制，联系系统服务商','code'=>1]);
        }

        $path = MEMBER_ID."/qrcode";
        $wx = Db::table("dt_wxminis")->where("memberid", MEMBER_ID)->find();
        $qr = new \myclass\Imageup($path);
        $page =  "pages/inside/boot_page/boot_page";//发布后生成带参数小程序码
        $scene = "staff,0,$deptid";
        $scene = str_replace(",","_",$scene);
        $ishyline = false;
        $appid = $wx['authorizer_appid'];
        $img = $qr->wxqrcode($page,$scene,$ishyline=false,$appid);
        /*$img = [
            'code' => 0,
            'msg' => '成功',
            'url' => "https://hs-1251609649.cos.ap-guangzhou.myqcloud.com/static%2Fmiaoke%2Fqrcode%2F1552103892.png",
        ];*/
        return json($img);
    }



}